package com.vehiclesecure.controller;

import com.vehiclesecure.model.EmergencyAlert;
import com.vehiclesecure.model.User;
import com.vehiclesecure.service.EmergencyAlertService;
import com.vehiclesecure.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 紧急警报控制器，处理与紧急警报相关的HTTP请求
 */
@RestController
@RequestMapping("/api/alerts")
public class EmergencyAlertController {

    private final EmergencyAlertService emergencyAlertService;
    private final UserService userService;

    @Autowired
    public EmergencyAlertController(EmergencyAlertService emergencyAlertService, UserService userService) {
        this.emergencyAlertService = emergencyAlertService;
        this.userService = userService;
    }
    
    /**
     * 获取当前登录用户
     * @return 当前登录用户对象
     */
    private User getCurrentUser() {
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        return (User) userService.loadUserByUsername(email);
    }

    /**
     * 创建新的紧急警报
     * @param alert 警报对象
     * @return 创建后的警报
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<EmergencyAlert> createAlert(@RequestBody EmergencyAlert alert) {
        User currentUser = getCurrentUser();
        
        // 检查用户是否有权访问该车辆
        if (!emergencyAlertService.hasAccessToVehicleAlerts(currentUser, alert.getVehicleId())) {
            return ResponseEntity.status(403).build(); // 权限不足
        }
        
        EmergencyAlert createdAlert = emergencyAlertService.createEmergencyAlert(alert);
        return ResponseEntity.ok(createdAlert);
    }

    /**
     * 获取所有警报
     * @return 警报列表
     */
    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<List<EmergencyAlert>> getAllAlerts() {
        User currentUser = getCurrentUser();
        
        // 对于普通用户，只返回其有权访问的警报
        List<EmergencyAlert> alerts = emergencyAlertService.getUserAccessibleAlerts(currentUser);
        return ResponseEntity.ok(alerts);
    }

    /**
     * 根据ID获取警报
     * @param id 警报ID
     * @return 警报对象
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<EmergencyAlert> getAlertById(@PathVariable String id) {
        User currentUser = getCurrentUser();
        
        Optional<EmergencyAlert> alertOptional = emergencyAlertService.getAlertById(id);
        
        if (alertOptional.isPresent()) {
            EmergencyAlert alert = alertOptional.get();
            
            // 检查用户是否有权访问该车辆的警报
            if (!emergencyAlertService.hasAccessToVehicleAlerts(currentUser, alert.getVehicleId())) {
                return ResponseEntity.status(403).build(); // 权限不足
            }
            
            return ResponseEntity.ok(alert);
        }
        
        return ResponseEntity.notFound().build();
    }

    /**
     * 根据车辆ID获取警报
     * @param vehicleId 车辆唯一标识符
     * @return 警报列表
     */
    @GetMapping("/vehicle/{vehicleId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<List<EmergencyAlert>> getAlertsByVehicleId(@PathVariable String vehicleId) {
        User currentUser = getCurrentUser();
        
        // 检查用户是否有权访问该车辆的警报
        if (!emergencyAlertService.hasAccessToVehicleAlerts(currentUser, vehicleId)) {
            return ResponseEntity.status(403).build(); // 权限不足
        }
        
        List<EmergencyAlert> alerts = emergencyAlertService.getAlertsByVehicleId(vehicleId);
        return ResponseEntity.ok(alerts);
    }

    /**
     * 获取所有活动的警报
     * @return 活动警报列表
     */
    @GetMapping("/active")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<List<EmergencyAlert>> getActiveAlerts() {
        User currentUser = getCurrentUser();
        
        // 对于普通用户，只返回其有权访问的活动警报
        List<EmergencyAlert> alerts = emergencyAlertService.getUserAccessibleActiveAlerts(currentUser);
        return ResponseEntity.ok(alerts);
    }

    /**
     * 解决警报
     * @param id 警报ID
     * @param requestBody 包含解决者信息的请求体
     * @return 解决后的警报
     */
    @PutMapping("/{id}/resolve")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<EmergencyAlert> resolveAlert(@PathVariable String id, @RequestBody Map<String, String> requestBody) {
        User currentUser = getCurrentUser();
        
        // 检查用户是否有权访问该警报
        Optional<EmergencyAlert> alertOptional = emergencyAlertService.getAlertById(id);
        if (alertOptional.isPresent()) {
            EmergencyAlert alert = alertOptional.get();
            if (!emergencyAlertService.hasAccessToVehicleAlerts(currentUser, alert.getVehicleId())) {
                return ResponseEntity.status(403).build(); // 权限不足
            }
        }
        
        String resolvedBy = requestBody.getOrDefault("resolvedBy", "SYSTEM");
        EmergencyAlert resolvedAlert = emergencyAlertService.resolveAlert(id, resolvedBy);
        return ResponseEntity.ok(resolvedAlert);
    }

    /**
     * 标记警报为无效
     * @param id 警报ID
     * @return 标记后的警报
     */
    @PutMapping("/{id}/invalidate")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<EmergencyAlert> markAlertAsInvalid(@PathVariable String id) {
        EmergencyAlert invalidAlert = emergencyAlertService.markAlertAsInvalid(id);
        return ResponseEntity.ok(invalidAlert);
    }

    /**
     * 获取时间范围内的警报
     * @param start 开始时间
     * @param end 结束时间
     * @return 警报列表
     */
    @GetMapping("/time-range")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER') or hasRole('SERVICE_PROVIDER')")
    public ResponseEntity<List<EmergencyAlert>> getAlertsInTimeRange(
            @RequestParam("start") String start, 
            @RequestParam("end") String end) {
        
        try {
            LocalDateTime startTime = LocalDateTime.parse(start);
            LocalDateTime endTime = LocalDateTime.parse(end);
            List<EmergencyAlert> alerts = emergencyAlertService.getAlertsInTimeRange(startTime, endTime);
            return ResponseEntity.ok(alerts);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}